<template>
  <div class="container">
    <a-card class="general-card">
      <!-- 搜索区域 -->
      <a-row>
        <a-col :flex="1">
          <a-form
            :model="searchForm"
            :label-col-props="{ span: 6 }"
            :wrapper-col-props="{ span: 18 }"
            label-align="left"
          >
            <a-row :gutter="16">
              <a-col :span="8">
                <a-form-item label="督办来源">
                  <a-select
                    v-model="searchForm.source"
                    :options="options.source"
                    placeholder="请选择督办来源"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="问题类型">
                  <a-select
                    v-model="searchForm.problemType"
                    :options="options.problemType"
                    placeholder="请选择问题类型"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="整改单位">
                  <a-select
                    v-model="searchForm.rectificationUnit"
                    :options="options.rectificationUnit"
                    placeholder="请选择整改单位"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-item label="整改期限">
                  <a-range-picker
                    v-model="searchForm.rfDateRange"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
        <a-divider style="height: 84px" direction="vertical" />
        <a-col :flex="'86px'" style="text-align: right">
          <a-space direction="vertical" :size="18">
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="resetForm">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>

      <!-- 工具栏 -->
      <a-divider style="margin-top: 0" />
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
            <a-button>统计导出</a-button>
          </a-space>
        </a-col>
      </a-row>

      <!-- 表格区域 -->
      <a-table
        :key="tableKey"
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        row-key="taskId"
        @page-change="onPageChange"
        @page-size-change="onPageSizeChange"
      >
        <template #requirements="{ record }">
          <a-tooltip :content="record.requirements || ''">
            <span>
              {{
                record.requirements
                  ? record.requirements.length > 10
                    ? record.requirements.substring(0, 10) + "..."
                    : record.requirements
                  : ""
              }}
            </span>
          </a-tooltip>
        </template>
        <template #rfUnits="{ record }">
          <a-tooltip
            :content="
              record.rfUnits
                ? record.rfUnits
                    .split(',')
                    .map((unitId) => getGroupName(Number(unitId)))
                    .filter((name) => name)
                    .join(', ')
                : ''
            "
          >
            <span>
              {{
                (() => {
                  const units = record.rfUnits
                    ? record.rfUnits
                        .split(",")
                        .map((unitId) => getGroupName(Number(unitId)))
                        .filter((name) => name)
                        .join(", ")
                    : "";
                  return units.length > 6
                    ? units.substring(0, 6) + "..."
                    : units;
                })()
              }}
            </span>
          </a-tooltip>
        </template>
        <template #rwUnits="{ record }">
          <a-tooltip
            :content="
              record.rwUnits
                ? record.rwUnits
                    .split(',')
                    .map((unitId) => getGroupName(Number(unitId)))
                    .filter((name) => name)
                    .join(', ')
                : ''
            "
          >
            <span>
              {{
                (() => {
                  const units = record.rwUnits
                    ? record.rwUnits
                        .split(",")
                        .map((unitId) => getGroupName(Number(unitId)))
                        .filter((name) => name)
                        .join(", ")
                    : "";
                  return units.length > 6
                    ? units.substring(0, 6) + "..."
                    : units;
                })()
              }}
            </span>
          </a-tooltip>
        </template>
        <template #remark="{ record }">
          <a-tooltip :content="record.remark || ''">
            <span>
              {{
                record.remark
                  ? record.remark.length > 5
                    ? record.remark.substring(0, 5) + "..."
                    : record.remark
                  : ""
              }}
            </span>
          </a-tooltip>
        </template>
        <template #action="{ record }">
          <template
            v-if="
              useUserStore().userId === record.auditor &&
              getStatusObj(record.status, record).key === 'review'
            "
          >
            <a-button
              type="primary"
              size="small"
              style="margin-right: 8px"
              @click="handleAudit(record)"
              >审批</a-button
            >
          </template>
          <template
            v-if="
              (useUserStore().userId === record.auditor ||
                useUserStore().userId === record.reportUser) &&
              getStatusObj(record.status, record).key !== 'withdraw' &&
              getStatusObj(record.status, record).key !== 'reviewed'
            "
          >
            <a-popconfirm content="确定要撤回吗?" @ok="handleRevoke(record)">
              <a-button type="outline" size="small">撤回</a-button>
            </a-popconfirm>
          </template>
          <!-- 重新发起按钮 -->
          <a-button
            v-if="
              record.reportUserId === useUserStore().userId &&
              getStatusObj(record.status, record).key === 'reject'
            "
            @click="handleRestart(record)"
            type="primary"
            size="small"
            style="margin-right: 8px"
            >重新发起</a-button
          >
          <!-- 接收按钮 -->
          <a-button
            v-if="
              record.rfUsers &&
              record.rfUsers
                .split(',')
                .includes(String(useUserStore().userId)) &&
              (getStatusObj(record.status, record).key === 'notReceived' ||
                getStatusObj(record.status, record).key === 'received') &&
              (!record.receiveUsers ||
                !record.receiveUsers.includes(String(useUserStore().userId)))
            "
            @click="handleReceive(record)"
            type="primary"
            size="small"
            style="margin-right: 8px"
          >
            接收
          </a-button>
          <a-button
            v-if="
              record.receiveUsers &&
              record.receiveUsers
                .split(',')
                .includes(String(useUserStore().userId)) &&
              ['received', 'processing', 'rejectReview'].includes(
                getStatusObj(record.status, record).key
              )
            "
            @click="handleProcess(record)"
            type="primary"
            size="small"
            style="margin-right: 8px"
          >
            反馈
          </a-button>
          <a-button
            v-if="
              record.reportUserId === useUserStore().userId &&
              [
                'pendingReviewing',
                'pendingReview',
                'pendingReviewed',
                'newReview',
              ].includes(getStatusObj(record.status, record).key)
            "
            @click="handleRecheck(record)"
            type="primary"
            size="small"
            style="margin-right: 8px"
          >
            复核
          </a-button>
        </template>

        <template #status="{ record }">
          <a-tag
            :color="getStatusColor(record.status)"
            style="cursor: pointer"
            @click="handleStatusClick(record)"
          >
            {{ getStatusObj(record.status, record).desc }}
          </a-tag>
        </template>
      </a-table>
    </a-card>

    <!-- 新增弹框 -->
    <TaskAddModal
      v-if="addModalVisible"
      :visible="addModalVisible"
      :form="addForm"
      :options="toRaw(options)"
      @update:visible="addModalVisible = $event"
      @update:opinion="addOpinion = $event"
      @refresh="fetchTaskList"
    />

    <!-- 审核弹框 -->
    <TaskReviewModal
      v-if="reviewModalVisible"
      :visible="reviewModalVisible"
      :form="reviewForm"
      :mode="reviewMode"
      :options="toRaw(options)"
      @update:visible="reviewModalVisible = $event"
      @update:opinion="reviewOpinion = $event"
      @refresh="fetchTaskList"
      @receive="fetchTaskList"
    />

    <!-- 编辑弹框 -->
    <TaskEditModal
      v-if="editModalVisible"
      :visible="editModalVisible"
      :form="editForm"
      :reviewMsg="editReviewMsg"
      :options="toRaw(options)"
      :tableData="tableData"
      :updateTableData="(newData) => {}"
      :fetchTaskList="() => fetchTaskList()"
      :parentFetchTaskList="() => fetchTaskList()"
      @update:visible="editModalVisible = $event"
      @refresh="fetchTaskList"
    />
    <!-- 反馈弹框 -->
    <TaskProcessModal
      v-if="processModalVisible"
      :visible="processModalVisible"
      :form="processForm"
      @update:visible="processModalVisible = $event"
      @refresh="fetchTaskList"
    />

    <!-- 复核弹框 -->
    <TaskRecheckModal
      v-if="recheckModalVisible"
      :visible="recheckModalVisible"
      :form="recheckForm"
      :users="recheckUsers"
      :task-id="recheckTaskId"
      @update:visible="recheckModalVisible = $event"
      @refresh="fetchTaskList"
    />
    <!-- 状态详情弹框 -->
    <a-modal
      v-model:visible="statusModalVisible"
      title="任务状态跟踪"
      :footer="false"
      width="800px"
      :mask-closable="true"
    >
      <div v-if="statusList.length" style="margin: 32px 0 16px 32px">
        <table
          style="
            width: 90%;
            margin: 0 auto;
            border-collapse: separate;
            border-spacing: 0 12px;
            font-size: 20px;
          "
        >
          <tr v-for="item in statusList" :key="item.groupName">
            <td style="text-align: left; font-weight: bold; width: 180px">
              {{ item.groupName }}：
            </td>
            <td
              style="text-align: left; width: 120px"
              :style="{
                color: String(item.status1 || '').startsWith('未')
                  ? 'red'
                  : '#1abc9c',
              }"
            >
              {{ item.status1 }}
            </td>
            <td
              style="text-align: left; width: 120px"
              :style="{
                color: String(item.status2 || '').startsWith('未')
                  ? 'red'
                  : '#1abc9c',
              }"
            >
              {{ item.status2 }}
            </td>
            <td
              style="text-align: left; width: 160px"
              :style="{
                color: String(item.status3 || '').startsWith('反馈未')
                  ? 'red'
                  : '#1abc9c',
              }"
            >
              {{ item.status3 }}
            </td>
          </tr>
        </table>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
// import { ref, reactive, watch, onMounted } from 'vue';
import { Message } from "@arco-design/web-vue";
import { queryGroupListAll } from "@/api/group";
import { queryNotifyList } from "@/api/task";
import { useAutoSearch } from "@/hooks/useAutoSearch";
import { useUserStore } from "@/store";
import { getUserList, queryUserByTask, queryAuditorByTask } from "@/api/user";
import {
  createTask,
  withdrawTask,
  getTaskById,
  getTaskAndProblemById,
  getTaskStatus,
} from "@/api/task";
import TaskReviewModal from "./TaskReviewModal.vue";
import TaskEditModal from "./TaskEditModal.vue";
import TaskAddModal from "./TaskAddModal.vue";
import TaskProcessModal from "./TaskProcessModal.vue";
import TaskRecheckModal from "./TaskRecheckModal.vue";
import { ref, reactive, watch, onMounted, toRaw, h } from "vue";
// 统一提前声明所有ref/reactive变量
const recheckModalVisible = ref(false);
const recheckForm = ref({});
const recheckUsers = ref([]); // 整改接收人数组
const recheckTaskId = ref(null);

const reviewModalVisible = ref(false);
const reviewForm = ref({});
const reviewOpinion = ref("");
const reviewMode = ref("review"); // 'review' 或 'receive'

const editModalVisible = ref(false);
const editForm = ref({});
const editReviewMsg = ref("");

const processModalVisible = ref(false);
const processForm = ref({});

const addOpinion = ref("");
const addModalVisible = ref(false);
const addFormRef = ref();
const addForm = reactive({
  source: "",
  problemType: "",
  requirements: "",
  leaderInstruction: false,
  leaderRemark: "",
  leaderFiles: "",
  problemList: [{ index: 1, problemDesc: "" }],
  rectificationUsers: [],
  rfDateRange: [],
  auditor: "",
  remark: "",
  attachments: "",
  reportDeptId: null,
  reportDeptName: "",
  reportUserId: null,
  reportUser: "",
  rectificationUnits: "",
});

const userTreeData = ref([]); // 整改人员树
const auditorOptions = ref([]); // 审核人下拉
const auditorTreeData = ref([]); // 审核人树
const groupData = ref([]); // 整改单位

const searchForm = reactive({
  source: "",
  problemType: "",
  requirements: "",
  rfDateRange: [],
  rectificationUnit: "",
  feedbackUnit: "",
  status: "",
});

const options = reactive({
  source: [
    { label: "司法部", value: "司法部" },
    { label: "司法局", value: "司法局" },
    { label: "监狱管理局", value: "监狱管理局" },
  ],
  problemType: [
    { label: "工作要点", value: "工作要点" },
    { label: "警务督察工作提示", value: "警务督察工作提示" },
    { label: "警务督察专报", value: "警务督察专报" },
    { label: "典型督察案例", value: "典型督察案例" },
    { label: "信息报表", value: "信息报表" },
    { label: "日常自查自报", value: "日常自查自报" },
  ],
  rectificationUnit: [],
  feedbackUnit: [],
  status: [],
});

const loading = ref(false);
const tableData = ref<any[]>([]);
const tableKey = ref<number>(0); // 用于强制表格重新渲染
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50],
});

const columns = [
  { title: "督办来源", dataIndex: "source" },
  { title: "问题类型", dataIndex: "problemType" },
  {
    title: "督察要求",
    dataIndex: "requirements",
    slotName: "requirements",
  },
  {
    title: "整改期限",
    dataIndex: "rfDateDisplay",
  },
  {
    title: "审核人",
    dataIndex: "auditor",
    render: ({ record }) => getUserName(record.auditor),
  },
  {
    title: "填报人",
    dataIndex: "reportUserId",
    render: ({ record }) => getUserName(record.reportUserId),
  },
  // {
  //   title: '填报单位',
  //   dataIndex: 'reportDeptId',
  //   render: ({ record }) => getGroupName(record.reportDeptId)
  // },
  {
    title: "整改单位",
    dataIndex: "rfUnits",
    slotName: "rfUnits",
  },
  {
    title: "反馈单位",
    dataIndex: "rwUnits",
    slotName: "rwUnits",
  },
  {
    title: "备注",
    dataIndex: "remark",
    slotName: "remark",
  },
  {
    title: "任务状态",
    dataIndex: "status",
    slotName: "status",
  },
  {
    title: "操作",
    dataIndex: "action",
    slotName: "action",
  },
];

// 状态详情弹框
const statusModalVisible = ref(false);
const statusDetailData = ref<any>({});
const statusList = ref<any[]>([]);

async function handleAudit(record) {
  try {
    const res = await getTaskById(record.taskId);
    if (res && (res.code === 200 || res.code === 0)) {
      const data = res.data || {};
      const formData = {
        ...data,
        rfUsers: data.rfUsers || [],
        rfUnits: data.rfUnits || [],
        auditorName: getUserName(data.auditor),
        attachments: data.taskFile ? [data.taskFile] : [],
        reportDeptName: getGroupName(data.reportDeptId),
        reportUser: getUserName(data.reportUserId),
      };
      // reviewForm.value = formData;
      reviewForm.value = JSON.parse(JSON.stringify(formData));
      reviewOpinion.value = "";
      reviewMode.value = "review";
      reviewModalVisible.value = true;
    } else {
      Message.error(res?.message || "获取任务详情失败");
    }
  } catch (e) {
    Message.error("获取任务详情失败");
  }
}

async function handleRevoke(record) {
  try {
    await withdrawTask(record.taskId);
    Message.success("撤回成功");
    fetchTaskList();
  } catch (e) {
    Message.error("撤回失败");
  }
}

// 处理状态点击
async function handleStatusClick(record) {
  try {
    const [detailRes, statusRes] = await Promise.all([
      getTaskById(record.taskId),
      getTaskStatus(record.taskId),
    ]);
    if (detailRes && (detailRes.code === 200 || detailRes.code === 0)) {
      const data = detailRes.data || {};
      const detailData = {
        ...data,
        auditorName: getUserName(data.auditor),
        reportDeptName: getGroupName(data.reportDeptId),
        reportUser: getUserName(data.reportUserId),
        // statusName: getStatusName(data.status),
        rfDateDisplay:
          data.rfStartDate && data.rfEndDate
            ? `${formatDate(data.rfStartDate)} - ${formatDate(data.rfEndDate)}`
            : "",
      };
      statusDetailData.value = detailData;
      statusModalVisible.value = true;
    }
    if (statusRes && (statusRes.code === 200 || statusRes.code === 0)) {
      statusList.value = statusRes.data || [];
    }
  } catch (e) {
    Message.error("获取任务详情失败");
  }
}

const fetchTaskList = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
    };
    // 处理整改期限时间范围，允许只选一个时间
    if (params.rfDateRange && Array.isArray(params.rfDateRange)) {
      const [start, end] = params.rfDateRange;
      if (start) params.rfStartDate = new Date(start).getTime();
      if (end) params.rfEndDate = new Date(end).getTime();
      delete params.rfDateRange;
    }
    const response = await queryNotifyList(params);
    if (response.code === 200 || response.code === 0) {
      // 处理日期
      const newData = response.data.rows.map((row) => ({
        ...row,
        rfDateDisplay:
          row.rfStartDate && row.rfEndDate
            ? `${formatDate(row.rfStartDate)} - ${formatDate(row.rfEndDate)}`
            : "",
      }));

      // 强制更新表格数据
      tableData.value = [...newData];
      pagination.total = response.data.page.totalRow;

      // 强制表格重新渲染
      tableKey.value++;
    } else {
      Message.error(response?.message || "获取任务列表失败");
    }
  } catch (error) {
    Message.error("获取任务列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  pagination.current = 1;
  fetchTaskList();
};
const onPageChange = (page) => {
  pagination.current = page;
  fetchTaskList();
};
const onPageSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.current = 1;
  fetchTaskList();
};

function resetForm() {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = Array.isArray(searchForm[key]) ? [] : "";
  });
}

function handleAdd() {
  const userStore = useUserStore();
  addForm.reportUserId = userStore.userId || "";
  addForm.reportUser = userStore.name || "";
  addForm.reportDeptId = userStore.group || "";
  addForm.reportDeptName = userStore.groupName || "";
  // fetchUserTreeData();
  fetchAuditorTreeData();
  addModalVisible.value = true;
}

onMounted(async () => {
  // 获取群组数据并筛选直属于监狱局的整改单位
  try {
    const res = await queryGroupListAll();
    // 确保 res.data 是数组
    const groupList = Array.isArray(res?.data) ? res.data : [];
    groupData.value = groupList;
    // 只保留 upGroupId 不为 null 的群组
    const units = groupList.filter((item) => item.upGroupId !== null);
    options.rectificationUnit = units.map((unit) => ({
      label: unit.groupName,
      value: unit.groupId,
    }));
  } catch (e) {
    Message.error("获取整改单位失败");
  }

  // 获取审核人选项（用于下拉选择）
  const userRes = await getUserList({});
  if (userRes?.data?.rows) {
    auditorOptions.value = userRes.data.rows.map((u) => ({
      label: u.name,
      value: u.userId,
    }));
  }
});

useAutoSearch(handleSearch);

const getGroupName = (groupId: number) => {
  const group = groupData.value.find((item) => item.groupId === groupId);
  return group ? group.groupName : `${groupId}`;
};
const getUserName = (userId: number) => {
  const user = auditorOptions.value.find((item) => item.value === userId);
  return user ? user.label : `${userId}`;
};

const statusMap = {
  review: { key: "review", step: 1, desc: "待审核" },
  withdraw: { key: "withdraw", step: 2, desc: "已撤回" },
  reject: { key: "reject", step: 3, desc: "已驳回" },
  notReceived: { key: "notReceived", step: 4, desc: "未接收" },
  received: { key: "received", step: 5, desc: "部分接收" },
  processing: { key: "processing", step: 6, desc: "待处理" },
  processed: { key: "processed", step: 7, desc: "部分处理" },
  rejectReview: { key: "rejectReview", step: 7, desc: "复核驳回" },
  pendingReviewing: { key: "pendingReviewing", step: 8, desc: "部分待复核" },
  pendingReview: { key: "pendingReview", step: 9, desc: "待复核" },
  pendingReviewed: { key: "pendingReviewed", step: 10, desc: "部分已复核" },
  newReview: { key: "newReview", step: 11, desc: "有新反馈待复核" },
  reviewed: { key: "reviewed", step: 12, desc: "已复核" },
};

//不同的用户显示的状态不同
const getStatusObj = (status: string, record: any) => {
  // console.log('【rf】', record.rfUsers);
  // console.log('【re】', record.receiveUsers);
  // console.log('【fb】', record.fbUsers);
  // console.log('【rj】', record.rjUsers);

  const userId = String(useUserStore().userId);
  // 处理 rfUsers、receiveUsers、fbUsers 可能为字符串或数组
  const rfArr =
    typeof record.rfUsers === "string"
      ? record.rfUsers.split(",")
      : record.rfUsers || [];
  const reArr =
    typeof record.receiveUsers === "string"
      ? record.receiveUsers.split(",")
      : record.receiveUsers || [];
  const fbArr =
    typeof record.fbUsers === "string"
      ? record.fbUsers.split(",")
      : record.fbUsers || [];
  const rjArr =
    typeof record.rjUsers === "string"
      ? record.rjUsers.split(",")
      : record.rjUsers || [];
  const step = statusMap[status]?.step || 0;
  // 1. 当前用户在rf里但不在re里，并且step>5
  if (rfArr.includes(userId) && !reArr.includes(userId) && step > 5) {
    return statusMap["notReceived"];
  }
  // 2. 当前用户在rf里但不在fb里，并且step>7
  if (rfArr.includes(userId) && !fbArr.includes(userId) && step > 7) {
    return statusMap["processing"];
  }
  // 3. 当前用户在rf里但不在rj里，显示临时状态
  if (rfArr.includes(userId) && rjArr.includes(userId)) {
    return statusMap["rejectReview"];
  }
  return statusMap[status] || { key: status, step: 0, desc: status };
};

const getStatusColor = (status: string) => {
  if (["notReceived", "received"].includes(status)) return "blue"; // 接收相关
  if (["processing", "processed"].includes(status)) return "purple"; // 处理相关
  if (
    [
      "pendingReviewing",
      "pendingReview",
      "pendingReviewed",
      "newReview",
    ].includes(status)
  )
    return "gold"; // 待复核相关
  if (status === "review") return "orange"; // 待审核
  if (status === "withdraw") return "gray"; // 已撤回
  if (status === "reject") return "red"; // 已驳回
  if (status === "reviewed") return "green"; // 已复核
  return "default";
};
function addProblemRow() {
  addForm.problemList.push({
    index: addForm.problemList.length + 1,
    problemDesc: "",
  });
}
function removeProblemRow(idx) {
  addForm.problemList.splice(idx, 1);
  addForm.problemList.forEach((item, i) => (item.index = i + 1));
}

async function fetchAuditorTreeData() {
  try {
    const res = await queryAuditorByTask();
    const tree = [];
    if (res && res.data) {
      Object.entries(res.data).forEach(([groupId, userList]) => {
        if (userList.length > 0) {
          tree.push({
            key: `group_${groupId}`, // 分组节点使用唯一的 key
            userId: Number(groupId),
            name: userList[0].groupName, // 分组名
            selectable: false, // 分组不可选
            children: userList.map((user) => ({
              key: user.userId, // 用户节点使用唯一的 key
              name: user.name + "-" + (user.deptName || ""), // 始终显示 userName-deptName
            })),
          });
        }
      });
    }
    auditorTreeData.value = tree;
  } catch (e) {
    Message.error("获取审核人失败");
  }
}

function handleAddCancel() {
  addModalVisible.value = false;
  // 重置表单数据
  Object.keys(addForm).forEach((key) => {
    if (key === "problemList") {
      addForm[key] = [{ index: 1, problemDesc: "" }];
    } else if (Array.isArray(addForm[key])) {
      addForm[key] = [];
    } else {
      addForm[key] = "";
    }
  });
}
function handleAddSubmit() {
  addFormRef.value.validate().then(async () => {
    try {
      // 这里可以根据后端DTO结构调整参数
      const payload = { ...addForm };
      // 只保留id，去掉名称
      payload.reportDept = payload.reportDeptId;
      payload.reportUser = payload.reportUserId;

      // 处理整改期限（传时间戳到rfStartDate和rfEndDate）
      if (
        Array.isArray(payload.rfDateRange) &&
        payload.rfDateRange.length === 2
      ) {
        const [start, end] = payload.rfDateRange;
        payload.rfStartDate = start ? new Date(start).getTime() : "";
        payload.rfEndDate = end ? new Date(end).getTime() : "";
      }
      delete payload.rfDateRange;
      // 处理附件（如有需要，提取url等）
      if (payload.attachments && payload.attachments.length) {
        payload.attachments = payload.attachments.map(
          (f) => f.url || f.response?.url || f
        );
      }
      // 提交表单
      await createTask(payload);
      Message.success("提交成功");
      addModalVisible.value = false;
      handleSearch(); // 刷新表格
    } catch (e) {
      Message.error("提交失败");
    }
  });
}

const addFormRules = {
  source: [{ required: true, message: "请选择督办来源" }],
  problemType: [{ required: true, message: "请选择问题类型" }],
  requirements: [{ required: true, message: "请输入督察要求" }],
  rectificationUsers: [{ required: true, message: "请选择整改人员" }],
  rfDateRange: [{ required: true, message: "请选择整改期限" }],
  auditor: [{ required: true, message: "请选择审核人" }],
};

watch(
  () => addForm.leaderInstruction,
  (val) => {
    if (!val) {
      addForm.leaderRemark = "";
      addForm.leaderFiles = [];
    }
  }
);

addForm.leaderInstruction = false;

function handleRectificationUsersChange(value) {
  console.log("整改人员选择变化:", value);
  // 获取所有用户节点的映射关系
  const userGroupMap = new Map();
  userTreeData.value.forEach((group) => {
    group.children.forEach((dept) => {
      dept.children.forEach((user) => {
        userGroupMap.set(user.key, {
          userId: user.key,
          groupId: group.userId,
          groupName: group.name,
          deptName: dept.name,
          userName: user.name,
        });
      });
    });
  });

  // 根据选中的用户key获取对应的组织信息
  const selectedGroups = new Map();
  const selectedUserKeys = value;

  selectedUserKeys.forEach((userKey) => {
    const userInfo = userGroupMap.get(userKey);
    if (userInfo) {
      if (selectedGroups.has(userInfo.groupId)) {
        // 发现重复组织
        Message.error("一个组织只能有一个整改接收人");
        // 移除重复的选择
        const newValue = value.filter((key) => key !== userKey);
        addForm.rectificationUsers = newValue;
        return;
      }
      selectedGroups.set(userInfo.groupId, userInfo.groupName);
    }
  });

  // 更新整改单位显示
  addForm.rectificationUnits = Array.from(selectedGroups.values()).join(", ");
}

function formatDate(ts) {
  if (!ts) return "";
  const d = new Date(ts);
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  return `${y}年${m}月${day}日`;
}

async function handleRestart(record) {
  try {
    const res = await getTaskById(record.taskId);
    if (res && (res.code === 200 || res.code === 0)) {
      const data = res.data || {};
      const formData = {
        ...data,
        rfUsers: data.rfUsers || [],
        rfUnits: data.rfUnits || [],
        auditorName: getUserName(data.auditor),
        attachments: data.taskFile ? [data.taskFile] : [],
        reportDeptName: getGroupName(data.reportDeptId),
        reportUser: getUserName(data.reportUserId),
      };
      editForm.value = JSON.parse(JSON.stringify(formData));
      editReviewMsg.value = record.msg || "";
      editModalVisible.value = true;
    } else {
      Message.error(res?.message || "获取任务详情失败");
    }
  } catch (e) {
    Message.error("获取任务详情失败");
  }
}

async function handleReceive(record) {
  try {
    const res = await getTaskById(record.taskId);
    if (res && (res.code === 200 || res.code === 0)) {
      const data = res.data || {};
      const formData = {
        ...data,
        rfUsers: data.rfUsers || [],
        rfUnits: data.rfUnits || [],
        auditorName: getUserName(data.auditor),
        attachments: data.taskFile ? [data.taskFile] : [],
        reportDeptName: getGroupName(data.reportDeptId),
        reportUser: getUserName(data.reportUserId),
      };
      reviewForm.value = JSON.parse(JSON.stringify(formData));
      reviewOpinion.value = "";
      reviewMode.value = "receive";
      reviewModalVisible.value = true;
    } else {
      Message.error(res?.message || "获取任务详情失败");
    }
  } catch (e) {
    Message.error("获取任务详情失败");
  }
}

async function handleRecheck(record) {
  try {
    // 获取任务详情
    const res = await getTaskById(record.taskId);
    if (res && (res.code === 200 || res.code === 0)) {
      const data = res.data || {};
      // 组装任务详情表单数据
      const formData = {
        ...data,
        rfUsers: data.rfUsers || [],
        rfUnits: data.rfUnits || [],
        auditorName: getUserName(data.auditor),
        attachments: data.taskFile ? [data.taskFile] : [],
        reportDeptName: getGroupName(data.reportDeptId),
        reportUser: getUserName(data.reportUserId),
      };
      recheckForm.value = JSON.parse(JSON.stringify(formData));
      recheckTaskId.value = data.taskId;
      recheckModalVisible.value = true;
    } else {
      Message.error(res?.message || "获取任务详情失败");
    }
  } catch (e) {
    Message.error("获取任务详情失败");
  }
}
async function handleProcess(record) {
  try {
    const res = await getTaskAndProblemById(record.taskId);
    if (res && (res.code === 200 || res.code === 0)) {
      const data = res.data || {};
      const formData = {
        ...data,
        rfUsers: data.rfUsers || [],
        rfUnits: data.rfUnits || [],
        auditorName: getUserName(data.auditor),
        attachments: data.taskFile ? [data.taskFile] : [],
        reportDeptName: getGroupName(data.reportDeptId),
        reportUser: getUserName(data.reportUserId),
      };
      processForm.value = JSON.parse(JSON.stringify(formData));
      processModalVisible.value = true;
    } else {
      Message.error(res?.message || "获取任务详情失败");
    }
  } catch (e) {
    Message.error("获取任务详情失败");
  }
}

function filterUserName(searchValue, node) {
  // 只对叶子节点（用户）进行搜索，且只用 name 字段
  return !node.children && node.name && node.name.includes(searchValue);
}
</script>

<style scoped>
.ml-2 {
  margin-left: 8px;
}
/* 只保留表格边框线加粗和分隔线明显，不设置背景色和字体色 */
.problem-table .arco-table-thead th,
.problem-table .arco-table-tbody td {
  border-color: #d9d9d9 !important;
}
.problem-table .arco-table {
  border-color: #d9d9d9 !important;
}
.problem-table .arco-table-tbody tr {
  border-bottom: 1px solid #d9d9d9 !important;
}
</style>
